package io.kumao.gateway.ratelimit;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.UUID;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

/**
 * 令牌键解析器
 *
 * @author 崔作利
 */
@Component
public class TokenKeyResolver implements KeyResolver {

    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        List<String> auths = headers.get(AUTHORIZATION);
        String key = CollectionUtils.isNotEmpty(auths) ? auths.get(0) : UUID.randomUUID().toString();
        return Mono.just(key);
    }
}
